<template>
  <van-list
    class="list"
    v-model:loading="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
  >
    <!-- <van-cell v-for="item in list" :key="item" :title="item" /> -->

    <van-card
      v-for="item in list"
      :key="item.id"
      :centered="true"
      :desc="item.desn"
      :title="item.title"
      :thumb="item.pic"
      @click="onClick(item.id)"
      @click-thumb="onClick(item.id)"
    >
      <template #tags>
        <van-tag plain><van-icon name="eye" /></van-tag>
        <van-tag plain><van-icon name="like" /></van-tag>
      </template>
    </van-card>
  </van-list>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { fetchNews } from '@/api/index.js'
import { useRouter } from 'vue-router'
const router = useRouter()

const total = ref(0)
const pageSize = ref(0)
const currentPage = ref(1)
const loading = ref(false)
const finished = ref(false)
const list = ref([])

const totalPageNum = computed(() => {
  //总页码
  return Math.ceil(total.value / pageSize.value)
})

onMounted(async () => {
  loading.value = true
  const response = await fetchNews(currentPage.value)
  console.log('list:', response.data)
  total.value = response.data.total
  pageSize.value = response.data.per_page
  // currentPage.value = response.data.current_page
  // List.value = response.data
  list.value.push(...response.data.data)
  // currentPage.value = currentPage.value + 1
  loading.value = false

  console.log('当前页码：', currentPage.value)
  if (currentPage.value === totalPageNum.value) {
    // 已经是最后一页
    finished.value = true
    return
  }
  console.log('当前页码：', currentPage.value)
})

const onLoad = async () => {
  currentPage.value = currentPage.value + 1
  console.log('当前页码：', currentPage.value)
  // 加载更多
  if (currentPage.value <= totalPageNum.value) {
    console.log('onload')
    loading.value = true
    const response = await fetchNews(currentPage.value)
    list.value.push(...response.data.data)
    loading.value = false
    if (currentPage.value === totalPageNum.value) {
      // 已经是最后一页
      finished.value = true
    }
  }
  console.log('当前页码：', currentPage.value)
}

const onClick = (id) => {
  router.push({ name: 'detail', params: { id } })
}
</script>

<style scoped>
.list {
  margin-bottom: 50px;
}
</style>
